<template>
  <div class="home_box">
    <div class="home_box_top">
      <el-row :gutter="24">
        <el-col :span="6">
          <div class="home_box_top_left">
            <div class="project_detail">
              <div>累计项目数量</div>
              <div class="project_detail_text">
                <!-- <img src="../static/icon/7.png" alt=""> -->
                <el-icon>
                  <Tickets />
                </el-icon>
                <p>11111</p>
                <p class="green">+16</p>
              </div>
            </div>
            <div class="project_desc">
              <div class="line"></div>
              <div>项目概览</div>
              <div class="project_desc_items">
                <div class="project_desc_item">
                  <div class="project_desc_item_text">37 <img src="../static/icon/1.png" alt=""
                      style="width: 16px;height: 16px;"> </div>
                  <div>项目总数</div>
                </div>
                <div class="project_desc_item">
                  <div class="project_desc_item_text">37 <img src="../static/icon/3.png" alt=""
                      style="width: 16px;height: 16px;"> </div>
                  <div>今日完成项目量</div>
                </div>
                <div class="project_desc_item">
                  <div class="project_desc_item_text">37 <img src="../static/icon/2.png" alt=""
                      style="width: 16px;height: 16px;"> </div>
                  <div>已交付项目量</div>
                </div>
                <div class="project_desc_item">
                  <div class="project_desc_item_text red">37 <img src="../static/icon/4.png" alt=""
                      style="width: 16px;height: 16px;"> </div>
                  <div>待交付项目量</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="18">
          <div class="home_box_top_right">
            <div class="top_chose">
              <div>
                <div class="line"></div>
                项目数据总览
              </div>

              <div class="navBar">
                <div :class="choseId == 0 ? 'active' : ''" @click="selectDataType(0)">
                  本周数据
                </div>
                <div :class="choseId == 1 ? 'active' : ''" @click="selectDataType(1)">
                  本月数据
                </div>
                <div :class="choseId == 2 ? 'active' : ''" @click="selectDataType(2)">
                  本年数据
                </div>
              </div>
            </div>
            <echarts1></echarts1>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="home_box_bottom">
      <el-row :gutter="24">
        <el-col :span="18">
          <div class="home_box_bottom_left">
            <div class="home_box_bottom_left_top">
              <div style="width: 120px;">
                <div class="line"></div>
                <div>最新项目 <el-icon>
                    <Refresh />
                  </el-icon></div>
              </div>
              <div @click="gotoMore">查看更多 <el-icon>
                  <ArrowRight />
                </el-icon></div>
            </div>
            <div class>
              <el-table ref="multipleTableRef" :data="tableData" height="350" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column fixed property="projectName" label="项目信息" width="240" show-overflow-tooltip />
                <el-table-column property="status" label="目前进度" width="120">
                  <template #default="scope">
                    <el-tag v-if="scope.row.status === '进行中'"  type="success">进行中</el-tag>
                    <el-tag v-if="scope.row.status === '未开始'" type="warning">未开始</el-tag>
                    <el-tag v-if="scope.row.status === '继续跟进'" type="danger">继续跟进</el-tag>
                    <el-tag v-if="scope.row.status === '已完成'" type="primary">已完成</el-tag>
                  </template>
                </el-table-column>
                <el-table-column property="projectLeader" label="数量" width="120" />
                <el-table-column property="projectProgress" label="交付日期" />
                <el-table-column property="projectProgress" label="目前状态" />
                <el-table-column property="address" label="操作" width="240">
                  <template #default="scope">
                    <el-button size="small" type="success"
                      @click="showProject(scope.$index, scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <div class="line"></div>
            <div>项目人员占比</div>
          </div>
          <echarts2 :legend="legendConfig" :series="seriesConfig"></echarts2>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="showDialogOverflowVisible" title="Tips" width="680" draggable overflow>
      <template #header> 项目详情 </template>
      <div>
        <el-form ref="ruleFormRef" style="max-width: 600px" status-icon label-width="auto" class="demo-ruleForm"
          label-position="top">
          <el-row>
            <el-col :span="11">
              <el-form-item label="项目名称:" prop="projectName">
                <el-input v-model="projectDetail.projectName" type="text" autocomplete="off" placeholder="请输入内容"
                  disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目进度:" prop="projectProgress">
                <el-input v-model="projectDetail.projectProgress" type="text" autocomplete="off" placeholder="请输入内容"
                  disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="负责人：" prop="projectLeader">
                <el-input v-model.number="projectDetail.projectLeader" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="交付日期：" prop="deliveryDate">
                <el-input v-model.number="projectDetail.deliveryDate" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="状态：" prop="status">
                <el-input v-model.number="projectDetail.status" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目人员：" prop="projectPersonnel">
                <el-input v-model.number="projectDetail.projectPersonnel" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialogOverflowVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watchEffect } from "vue";
import echarts1 from "../components/echarts1.vue";
import echarts2 from "../components/echarts2.vue";
import webRequest from "../utils/request";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

export default {
  components: { echarts1, echarts2 },
  setup() {
    const router = useRouter();
    const showDialogOverflowVisible = ref(false);
    const choseId = ref(0)
    let tableData = ref([]);
    const legendConfig = ref({
      bottom: '5%',
      left: 'center'
    })

    let datas = ref([]);
    const seriesConfig = reactive({
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      padAngle: 5,
      itemStyle: {
        borderRadius: 10
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    });
    // 定义响应式数据
    const projectDetail = ref({
      name: "",
      sex: "",
      birth: "",
      phone: "",
      political: "",
      education: "",
      department: "",
      position: "",
      entryTime: "",
      status: "",
    });
    const tableRowClassName = ({
      row,
      rowIndex,
    }) => {
      console.log(row, rowIndex, rowIndex === 1);
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    }
    const getProjectByPageData = async () => {
      const res = await webRequest.projectDetail.getProjectAllMethod()
      tableData.value = res.data.data
      console.log(res, res.data);
    }

    const gotoMore = () => {
      router.push("/projectCenter");
    }
    const selectDataType = (index) => {
      choseId.value = index
      if (index == 0) {
        getProjectByDateMethod("week")
      } else if (index == 1) {
        getProjectByDateMethod("month")
      }
      else {
        getProjectByDateMethod("year")
      }
      ElMessage({
        message: "数据加载成功",
        grouping: true,
        type: "success",
      });
    }
    const getProjectByDateMethod = async (date) => {
      const res = await webRequest.projectDetail.getProjectByDate(date)
      console.log(res, res.data);
    }

    const showProject = (index, item) => {
      console.log(showDialogOverflowVisible);
      projectDetail.value = item;
      showDialogOverflowVisible.value = true;
    };
    // 获取人员id以及对应的部门来展示echarts
    const departmentCountMap = new Map();
    const showEcharts = async (ids) => {
      // 获取所有人员信息
      const res = await webRequest.people.getAllPeoleInfoMethod();
      const data = res.data.data;

      // 根据传入的项目负责人 id 筛选出该项目的人员信息
      const projectPeople = data.filter(item => ids.includes(item.id));
      console.log('Project People:', projectPeople);

      // 清空 departmentCountMap 和 datas，以便重新计算
      departmentCountMap.clear();
      datas = [];

      // 计算各个部门的人数
      projectPeople.forEach(person => {
        const department = person.department.toLowerCase().trim(); // 标准化部门名称
        const currentCount = departmentCountMap.get(department) || 0;
        departmentCountMap.set(department, currentCount + 1);
        console.log(department, currentCount, departmentCountMap.get(department), 'dsjkhfsdkjfhsdjkfhdsjkh');
      });

      // 将部门名称和人数转换为适合 ECharts 使用的数据格式
      datas = [...departmentCountMap.entries()].map(([name, value]) => ({ name, value }));
      console.log('Department Count Map:', departmentCountMap);
      console.log('Datas:', datas);
      console.log('Series Config Data:', seriesConfig.data);
      // 将多次获得的datas的值按照部门名称进行合并
      datas.forEach((item) => {
        const index = seriesConfig.data.findIndex((dataItem) => dataItem.name === item.name);
        if (index === -1) {
          seriesConfig.data.push(item);
        } else {
          seriesConfig.data[index].value += item.value;
        }
      });
      // 更新 seriesConfig 的数据
    };


    const handleSelectionChange = (val) => {
      console.log(val, 'kjdsflsadgfsdkhjagfdhsjk');
      if (val.length == 0) {
        // 清空数据
        seriesConfig.data = [];
        return;
      }
      val.map((item) => {
        showEcharts(item.projectLeaderId);
      });

    };
    getProjectByPageData()
    return { legendConfig, seriesConfig, showEcharts, tableData, gotoMore, showProject, showDialogOverflowVisible, projectDetail, choseId, selectDataType, getProjectByDateMethod, tableRowClassName, handleSelectionChange };
  },
};
</script>

<style lang="less" scoped>
.green {
  color: #00ff00 !important;
}

.el-table .warning-row {
  color: #00ff00;
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.top_chose {
  display: flex;
}

.active {
  color: black !important;
  background: white !important;
  border-radius: 10px;
  // 一秒动画
  transition: all .5s;
}

.navBar {
  display: flex;
  background: #1E63EE;
  width: 280px;
  color: white;
  border-radius: 10px;
  padding: 4px;
  margin-left: 120px;

  div {
    flex: 1;
    text-align: center;
    color: white;
  }
}

.project_desc_item_text {
  color: #2863DA;
  font-size: 30px;
}

.red {
  color: #F8473F !important;

}

.home_box {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  padding: 20px;
  box-sizing: border-box;
  flex-direction: column;

  .home_box_top {
    width: 100%;
  }

  .home_box_top_left {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    width: 100%;

    .project_detail {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      flex-direction: column;
      text-align: center;
      background-color: #2863DA;
      padding: 20px;
      border-radius: 10px;
      color: white;

      .project_detail_text {
        margin-top: 20px;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 16px;
          height: 16px;
          margin-right: 10px;
        }

        p {
          font-size: 20px;
          margin: 0;
          color: white;
        }
      }
    }

    .project_desc {
      margin-bottom: 20px;
    }

    .project_desc_items {
      text-align: center;
      display: flex;
      flex-wrap: wrap;
    }

    .project_desc_item {
      width: 40%;
    }
  }

  .home_box_top_right {
    width: 100%;
    height: 100%;
  }
}

.home_box_bottom {
  .home_box_bottom_left {
    background-color: white;

    .home_box_bottom_left_top {
      display: flex;
      justify-content: space-between;
      padding: 20px;

      .line {
        border-top: 1px solid hsla(0, 0%, 100%, .05);
        border-bottom: 1px solid rgba(0, 0, 0, .2);
      }
    }
  }
}
</style>